<?php
namespace app\common\model\cms;

use app\common\model\BaseModel;
use org\util\DbHelper;
use think\facade\Cache;

class MoudleMetaModel extends BaseModel
{
    protected $name = 'cms_moudle_meta';
    protected $pk='id';

    protected $type=[];

    /**
     * 添加字段
     * @param $data
     * @return bool|void
     * @throws \think\exception\PDOException
     */
    public function addData($data) {
        self::startTrans();
        try{
            if(DbHelper::checkField($data['table_name'],$data['field_name'])===true) exception('该字段已存在！');
            if($this->where('field_name',$data['field_name'])->find()) exception('该字段已存在配置项！',40001);
            $fieldSql='';
            switch ($data['data_type']){
                case 'char':
                case 'varchar':
                    $fieldSql = "ALTER TABLE {$data['table_name']} ADD {$data['field_name']} {$data['data_type']}({$data['data_length']}) DEFAULT '' COMMENT '{$data['display_name']}'";
                    break;
                case 'tinyint':
                case 'smallint':
                case 'int':
                case 'float':
                case 'decimal':
                    $fieldSql = "ALTER TABLE {$data['table_name']} ADD {$data['field_name']} {$data['data_type']}({$data['data_length']}) DEFAULT '0' COMMENT '{$data['display_name']}'";
                    break;
                case 'text':
                case 'mediumtext':
                    $fieldSql = "ALTER TABLE {$data['table_name']} ADD {$data['field_name']} {$data['data_type']} COMMENT '{$data['display_name']}'";
                    break;
            }
            if(empty($fieldSql)) exception('字段类型不正确！',40001);
            $this->execute($fieldSql);
            $info = self::create($data);
            $this->updateCache($info['moudle_id']);
            self::commit();
        }catch (\Exception $e){
        	self::rollback();
        }
        return $info;
    }

    /**
     * 修改字段信息
     * @param $data
     */
    public function editData($data) {
        self::update($data);
        $info = $this->where('id',$data['id'])->find();
        $this->updateCache($info['moudle_id']);
    }
    /**
     * 删除字段
     * @param $id
     * @return bool|void
     */
    public function delData($id){
        self::startTrans();
        try{
            $info = $this->where('id',$id)->find();
            if($info['is_system']==1) exception('系统字段不允许删除！');
            $sql = "ALTER TABLE {$info['table_name']} DROP {$info['field_name']}";
            $this->execute($sql);
            $this->where('id',$id)->delete();
            $this->updateCache($info['moudle_id']);
            self::commit();
        }catch (\Exception $e){
            self::rollback();
            exception($e->getMessage(),$e->getCode());
        }
        return true;
    }

    /**
     * 缓存表数据
     */
    public function updateCache($moudleId){
        $info = MoudleModel::where('id',$moudleId)->field("id,name,table_name,remark,status,show_order")->find()->toArray();
        $info['meta'] = $this->where('moudle_id',$moudleId)->order('show_order asc')->select()->toArray();
        Cache::set('cms_moudle_'.$moudleId,$info);
    }
    /**
     * cms模型字段初始化
     * @param $tableName
     * @param $moudleId
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fieldInit($tableName,$moudleId){
        $dataList=[
            [
                'moudle_id'=>$moudleId,
                'table_name'=>$tableName,
                'display_name'=>'栏目分类',
                'field_name'=>'class_id',
                'default_value'=>'0',
                'data_type'=>'int',
                'data_length'=>'11',
                'form_config'=>json_encode(["list-data"=>'$class',"items-key"=>"id","items-name"=>"_name","empty-option"=>"|请选择栏目"],JSON_UNESCAPED_UNICODE),
                'form_type'=>'select',
                'valid'=>'require',
                'show_order'=>'1',
                'is_system'=>'1',
                'is_main'=>'1',
            ],
            [
                'moudle_id'=>$moudleId,
                'table_name'=>$tableName,
                'display_name'=>'标题',
                'field_name'=>'title',
                'default_value'=>'',
                'data_type'=>'varchar',
                'data_length'=>'255',
                'form_config'=>json_encode(["placeholder"=>"请输入标题"],JSON_UNESCAPED_UNICODE),
                'form_type'=>'text',
                'valid'=>'require',
                'show_order'=>'2',
                'is_system'=>'1',
                'is_main'=>'1',
            ],
            [
                'moudle_id'=>$moudleId,
                'table_name'=>$tableName,
                'display_name'=>'缩略图',
                'field_name'=>'thumb_url',
                'default_value'=>'',
                'data_type'=>'varchar',
                'data_length'=>'255',
                'form_config'=>'',
                'form_type'=>'image',
                'valid'=>'',
                'show_order'=>'3',
                'is_system'=>'1',
                'is_main'=>'1',
            ],
            [
                'moudle_id'=>$moudleId,
                'table_name'=>$tableName,
                'display_name'=>'关键词',
                'field_name'=>'keywords',
                'default_value'=>'',
                'data_type'=>'varchar',
                'data_length'=>'255',
                'form_config'=>'',
                'form_type'=>'tags',
                'valid'=>'',
                'show_order'=>'4',
                'is_system'=>'1',
                'is_main'=>'1',
            ],
            [
                'moudle_id'=>$moudleId,
                'table_name'=>$tableName,
                'display_name'=>'描述',
                'field_name'=>'description',
                'default_value'=>'',
                'data_type'=>'varchar',
                'data_length'=>'255',
                'form_config'=>json_encode(["placeholder"=>"请输入描述"],JSON_UNESCAPED_UNICODE),
                'form_type'=>'textarea',
                'valid'=>'',
                'show_order'=>'5',
                'is_system'=>'1',
                'is_main'=>'1',
            ],
            [
                'moudle_id'=>$moudleId,
                'table_name'=>$tableName,
                'display_name'=>'内容',
                'field_name'=>'content',
                'default_value'=>'',
                'data_type'=>'mediumtext',
                'data_length'=>'0',
                'form_config'=>'',
                'form_type'=>'ckeditor',
                'valid'=>'',
                'show_order'=>'6',
                'is_system'=>'1',
                'is_main'=>'1',
            ],
            [
                'moudle_id'=>$moudleId,
                'table_name'=>$tableName,
                'display_name'=>'排序',
                'field_name'=>'show_order',
                'default_value'=>'0',
                'data_type'=>'int',
                'data_length'=>'11',
                'form_config'=>json_encode(["placeholder"=>"请输入排序"],JSON_UNESCAPED_UNICODE),
                'form_type'=>'text',
                'valid'=>'integer',
                'show_order'=>'7',
                'is_system'=>'1',
                'is_main'=>'0',
            ],
            [
                'moudle_id'=>$moudleId,
                'table_name'=>$tableName,
                'display_name'=>'审核',
                'field_name'=>'is_audit',
                'default_value'=>'1',
                'data_type'=>'tinyint',
                'data_length'=>'1',
                'form_config'=>json_encode(["list-data"=>[["id"=>1,"name"=>"通过"],["id"=>0,"name"=>"拒绝"]]],JSON_UNESCAPED_UNICODE),
                'form_type'=>'radio',
                'valid'=>'integer',
                'show_order'=>'8',
                'is_system'=>'1',
                'is_main'=>'0',
            ]
        ];
        $this->saveAll($dataList);
    }
}